//
//  SKTagView.m
//
//  Created by Day Ling on 15/1/12.
//  Copyright (c) 2015 Day Ling. All rights reserved.
//

#import "SKTagView.h"
#import "SKTagButton.h"


@interface SKTagView ()

@property (strong, nonatomic, nullable) NSMutableArray *tags;
@property (assign, nonatomic) BOOL didSetup;
@property (nonatomic,assign) BOOL isIntrinsicWidth;  //!<是否宽度固定
@property (nonatomic,assign) BOOL isIntrinsicHeight; //!<是否高度固定
//@property (nonatomic, strong) NSMutableArray *bntArray;//所有的按钮
//设置外间距
@property(nonatomic,assign) CGFloat top;
@property(nonatomic,assign) CGFloat left;
@property(nonatomic,assign) CGFloat bottom;
@property(nonatomic,assign) CGFloat right;
//内间距
@property(nonatomic, assign) CGFloat lrmogi;//左右间距
@property(nonatomic, assign) CGFloat tbmogi;//山下间距
@property(nonatomic, assign) CGFloat rowHeight;//cell高度

@property(nonatomic,strong) UIColor *borderColor;//文字和边框颜色
@property(nonatomic,strong) UIColor *bgcolor;//背景颜色

@property(nonatomic,assign) CGFloat fsize;//字体大小
@property(nonatomic,assign) CGFloat borderWidth;//边框宽度
@property(nonatomic,assign) CGFloat corderRadius;//边框倒角

@property(nonatomic,assign) CGFloat tagmogi;//每个tag左右间隙
@property(nonatomic,assign) BOOL bool1;
@property(nonatomic,assign) BOOL bool2;
@property(nonatomic,assign) BOOL bool3;

@end

@implementation SKTagView
-(void)setUpUIEdgeInsetstop:(CGFloat)top left:(CGFloat)left bottom:(CGFloat)bottom right:(CGFloat)right lrmogi:(CGFloat)lrmogi tbmogi:(CGFloat)tbmogi rowHeight:(CGFloat)rowHeight{
    self.bool1 = YES;
    self.top = top;
    self.left = left;
    self.bottom = bottom;
    self.right = right;
    self.lrmogi = lrmogi;
    self.tbmogi = tbmogi;
    self.rowHeight = rowHeight;
}

-(void)setUpBorderColor:(UIColor *)borderColor baColor:(UIColor *)bgcolor {
    self.bool2 = YES;
    self.borderColor = borderColor;
    self.bgcolor = bgcolor;
}

-(void)setUpLabelFont:(CGFloat)fsize borderWidth:(CGFloat)borderWidth corderRadius:(CGFloat)corderRadius tagmogi:(CGFloat)tagmogi{
    self.bool3 = YES;
    self.fsize = fsize;
    self.borderWidth = borderWidth;
    self.corderRadius = corderRadius;
    self.tagmogi = tagmogi;
}
#pragma mark - private mehtods

- (void)initNoWithType:(SKTagViewStyle)type data:(NSArray *)dataArray{
    
    self.preferredMaxLayoutWidth = CGRectGetWidth(self.frame);
    self.padding = UIEdgeInsetsMake(12.f, 15.f, 12.f, 15.f);//上左下右
    self.interitemSpacing = 15;//cell左右间的间隙
    self.lineSpacing = 16;//cell上下间的间隙
    self.regularHeight = 31.f;//cell高度
    [self removeAllTags];
    self.tagViewStyle = type;
    if (self.bool1) {
        self.padding = UIEdgeInsetsMake(self.top, self.left, self.bottom, self.right);
        self.interitemSpacing = self.lrmogi;//cell左右间的间隙
        self.lineSpacing = self.tbmogi;//cell上下间的间隙
        self.regularHeight = self.rowHeight;//cell高度
    }
    //Add Tagse
    [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SKTag *tag = [SKTag tagWithText:obj];
        tag.textColor = [UIColor grayColor];
        tag.selectTextColor = [UIColor whiteColor];
        tag.fontSize = 14.f;
        tag.padding = UIEdgeInsetsMake(5.f, 12.f, 5.f, 12.f);
        
        tag.bgColor = [UIColor clearColor];
        tag.selectBgColor = [UIColor colorWithRed:0.2 green:0.3 blue:0.5 alpha:0.5];
        
        tag.borderColor = [UIColor grayColor];
        tag.selectborderColor = [UIColor clearColor];
        tag.borderWidth = 1.f;
        tag.cornerRadius = 15.5;
        
        if (self.bool2) {
            tag.textColor =  self.borderColor ;
            tag.selectTextColor =  self.borderColor ;
            tag.bgColor =  self.bgcolor;
            tag.selectBgColor = self.bgcolor;
            tag.borderColor =  self.borderColor ;
            tag.selectborderColor =  self.borderColor ;
        }
        if (self.bool3) {
            tag.fontSize = self.fsize;
            tag.borderWidth = self.borderWidth;
            tag.cornerRadius = self.corderRadius;
            tag.padding = UIEdgeInsetsMake(0.f, self.tagmogi, 0.f, self.tagmogi);

        }
        [self addTag:tag];

    }];
    
    self.didTapTagAtIndex = ^(NSUInteger index , UIButton * _Nonnull bnt){
        NSLog(@"%ld",index);
    };
}
-(CGFloat)calculateWidthArr:(NSArray *)arr {
    CGFloat allWidth = 0;
    for (int i =0 ; i<arr.count; i++) {
        NSString *str = arr[i];
        CGFloat titleWidth = [self calculateRowWidth:str];
        allWidth = allWidth + titleWidth+2;
    }
    return allWidth+(self.lrmogi*(arr.count-1))+self.left+self.right;
}
//计算cell宽度
- (CGFloat)calculateRowWidth:(NSString *)string{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:self.fsize]};  //指定字号
    CGRect rect = [string boundingRectWithSize:CGSizeMake(0, self.rowHeight)/*计算宽度时要确定高度*/ options:NSStringDrawingUsesLineFragmentOrigin |
                   NSStringDrawingUsesFontLeading attributes:dic context:nil];
    return rect.size.width+(self.tagmogi*2);
}
// 重写setter给bool赋值
- (void)setRegularWidth:(CGFloat)intrinsicWidth
{
    if (_regularWidth != intrinsicWidth) {
        _regularWidth = intrinsicWidth;
        if (intrinsicWidth == 0) {
            self.isIntrinsicWidth = NO;
        }
        else
        {
            self.isIntrinsicWidth = YES;
        }
    }
    
}

- (void)setRegularHeight:(CGFloat)intrinsicHeight
{
    if (_regularHeight != intrinsicHeight) {
        _regularHeight = intrinsicHeight;
        if (intrinsicHeight == 0)
        {
            self.isIntrinsicHeight = NO;
        }
        else
        {
            self.isIntrinsicHeight = YES;
        }
    }
}

#pragma mark - Lifecycle

-(CGSize)intrinsicContentSize {
    if (!self.tags.count) {
        return CGSizeZero;
    }
    
    NSArray *subviews = self.subviews;
    UIView *previousView = nil;
    CGFloat topPadding = self.padding.top;
    CGFloat bottomPadding = self.padding.bottom;
    CGFloat leftPadding = self.padding.left;
    CGFloat rightPadding = self.padding.right;
    CGFloat itemSpacing = self.interitemSpacing;
    CGFloat lineSpacing = self.lineSpacing;
    CGFloat currentX = leftPadding;
    CGFloat intrinsicHeight = topPadding;
    CGFloat intrinsicWidth = leftPadding;
    
    if (!self.singleLine && self.preferredMaxLayoutWidth > 0) {
        NSInteger lineCount = 0;
        for (UIView *view in subviews) {
            CGSize size = view.intrinsicContentSize;
            // 宽度和高度通过参数的0或者非0来进行赋值
            CGFloat width = self.isIntrinsicWidth?self.regularWidth:size.width;
            CGFloat height = self.isIntrinsicHeight?self.regularHeight:size.height;
            if (previousView) {
                //                CGFloat width = size.width;
                currentX += itemSpacing;
                if (currentX + width + rightPadding <= self.preferredMaxLayoutWidth) {
                    currentX += width;
                } else {
                    lineCount ++;
                    currentX = leftPadding + width;
                    intrinsicHeight += height;
                }
            } else {
                lineCount ++;
                intrinsicHeight += height;
                currentX += width;
            }
            previousView = view;
            intrinsicWidth = MAX(intrinsicWidth, currentX + rightPadding);
        }
        
        intrinsicHeight += bottomPadding + lineSpacing * (lineCount - 1);
    } else {
        for (UIView *view in subviews) {
            CGSize size = view.intrinsicContentSize;
            intrinsicWidth += self.isIntrinsicWidth?self.regularWidth:size.width;
        }
        intrinsicWidth += itemSpacing * (subviews.count - 1) + rightPadding;
        intrinsicHeight += ((UIView *)subviews.firstObject).intrinsicContentSize.height + bottomPadding;
    }
    
    return CGSizeMake(intrinsicWidth, intrinsicHeight);
}

- (void)layoutSubviews {
    if (!self.singleLine) {
        self.preferredMaxLayoutWidth = self.frame.size.width;
    }
    
    [super layoutSubviews];
    
    [self layoutTags];
}

#pragma mark - Custom accessors

- (NSMutableArray *)tags {
    if(!_tags) {
        _tags = [NSMutableArray array];
    }
    return _tags;
}

//- (NSMutableArray *)bntArray{
//    if (!_bntArray) {
//        _bntArray = [NSMutableArray array];
//    }
//    return _bntArray;
//}

- (void)setPreferredMaxLayoutWidth: (CGFloat)preferredMaxLayoutWidth {
    if (preferredMaxLayoutWidth != _preferredMaxLayoutWidth) {
        _preferredMaxLayoutWidth = preferredMaxLayoutWidth;
        _didSetup = NO;
        [self invalidateIntrinsicContentSize];
    }
}

#pragma mark - Private

- (void)layoutTags {
    if (self.didSetup || !self.tags.count) {
        return;
    }
    
    NSArray *subviews = self.subviews;
    UIView *previousView = nil;
    CGFloat topPadding = self.padding.top;
    CGFloat leftPadding = self.padding.left;
    CGFloat rightPadding = self.padding.right;
    CGFloat itemSpacing = self.interitemSpacing;
    CGFloat lineSpacing = self.lineSpacing;
    CGFloat currentX = leftPadding;
    
    if (!self.singleLine && self.preferredMaxLayoutWidth > 0) {
        for (UIView *view in subviews) {
            CGSize size = view.intrinsicContentSize;
            CGFloat width1 = self.isIntrinsicWidth?self.regularWidth:size.width;
            CGFloat height1 = self.isIntrinsicHeight?self.regularHeight:size.height;
            if (previousView) {
                //                CGFloat width = size.width;
                currentX += itemSpacing;
                if (currentX + width1 + rightPadding <= self.preferredMaxLayoutWidth) {
                    view.frame = CGRectMake(currentX, CGRectGetMinY(previousView.frame), width1, height1);
                    currentX += width1;
                } else {
                    CGFloat width = MIN(width1, self.preferredMaxLayoutWidth - leftPadding - rightPadding);
                    view.frame = CGRectMake(leftPadding, CGRectGetMaxY(previousView.frame) + lineSpacing, width, height1);
                    currentX = leftPadding + width;
                }
            } else {
                CGFloat width = MIN(width1, self.preferredMaxLayoutWidth - leftPadding - rightPadding);
                view.frame = CGRectMake(leftPadding, topPadding, width, height1);
                currentX += width;
            }
            NSLog(@"1--：%@",NSStringFromCGRect(view.frame));
            NSLog(@"2--：%f",self.allWidth);
            previousView = view;
        }
    } else {
        for (UIView *view in subviews) {
            CGSize size = view.intrinsicContentSize;
            view.frame = CGRectMake(currentX, topPadding, self.isIntrinsicWidth?self.regularWidth:size.width, self.isIntrinsicHeight?self.regularHeight:size.height);
            currentX += self.isIntrinsicWidth?self.regularWidth:size.width;
            
            previousView = view;

        }
    }
    
    self.didSetup = YES;
}

#pragma mark - IBActions

- (void)onTag:(SKTagButton *)btn{
    if (self.tagViewStyle == SKTagViewStyleDefault) {
        
    }
    if(self.tagViewStyle == SKTagViewStyleOnlySelectOne){
        btn.selected = YES;
        [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SKTagButton *bnt = (SKTagButton *)obj;
            if (bnt != btn) {
                bnt.selected = NO;
                if (bnt.skTag.borderColor) {
                    bnt.layer.borderColor = btn.skTag.borderColor.CGColor;
                }
            }
        }];
    }
    if (self.tagViewStyle == SKTagViewStyleCanSelectMore) {
        btn.selected = !btn.selected;
    }
    
    if (btn.skTag.borderColor) {
        if (!btn.selected) {
            btn.layer.borderColor = btn.skTag.borderColor.CGColor;
        }
    }
    
    if (btn.skTag.selectborderColor) {
        if (btn.selected) {
            btn.layer.borderColor = btn.skTag.selectborderColor.CGColor;
        }
    }
    
    if (self.didTapTagAtIndex) {
        self.didTapTagAtIndex([self.subviews indexOfObject:btn] ,btn);
    }
}

#pragma mark - Public

- (void)addTag:(SKTag *)tag {
    NSParameterAssert(tag);
    SKTagButton *btn = [SKTagButton buttonWithTag:tag];
    [btn addTarget:self action:@selector(onTag:) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview: btn];
    [self.tags addObject: tag];
    
    self.didSetup = NO;
    [self invalidateIntrinsicContentSize];
}


- (void)insertTag:(SKTag *)tag atIndex:(NSUInteger)index {
    NSParameterAssert(tag);
    if (index + 1 > self.tags.count) {
        [self addTag:tag];
    } else {
        SKTagButton *btn = [SKTagButton buttonWithTag:tag];
        [btn addTarget:self action: @selector(onTag:) forControlEvents:UIControlEventTouchUpInside];
        [self insertSubview:btn atIndex:index];
        [self.tags insertObject:tag atIndex:index];
        
        self.didSetup = NO;
        [self invalidateIntrinsicContentSize];
        

    }
}

- (void)removeTag: (SKTag *)tag {
    NSParameterAssert(tag);
    NSUInteger index = [self.tags indexOfObject: tag];
    if (NSNotFound == index) {
        return;
    }
    
    [self.tags removeObjectAtIndex: index];
    if (self.subviews.count > index) {
        [self.subviews[index] removeFromSuperview];
    }
    
    self.didSetup = NO;
    [self invalidateIntrinsicContentSize];
}

- (void)removeTagAtIndex: (NSUInteger)index {
    if (index + 1 > self.tags.count) {
        return;
    }
    
    [self.tags removeObjectAtIndex: index];
    if (self.subviews.count > index) {
        [self.subviews[index] removeFromSuperview];
    }
    
    self.didSetup = NO;
    [self invalidateIntrinsicContentSize];
}

- (void)removeAllTags {
    [self.tags removeAllObjects];
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    
    self.didSetup = NO;
    [self invalidateIntrinsicContentSize];
}

@end
